<template>
    <div class="yemian">
        <div class="header">
            <img :src="require('@/assets/AI.png')" alt="AILogo" class="img1">
        </div>
        <div class="bigbox">
            <div class="content">
                <!-- 左侧 手机扫码登录 部分 -->
                <div class="saoma">
                    <div class="ma-tltle">暑培大一</div>
                    <img :src="require('@/assets/peixun.png')" alt="peixunLogo" class="img2">
                    <div class="ma-how">
                        <p>
                            <span class="dakai">打开</span>
                            <span class="app">AI大模型</span>
                            <span class="dianji">查看</span>
                        </p>
                        <span class="where">讯飞人工智能学院</span>
                    </div>
                </div>

                <!-- 右侧 登录方式切换 区域 -->
                <div class="denglu">
                    <!-- 登录方式 tabs -->
                    <div class="ways">
                        <button :class="{ active: isPasswordLogin, 'text-orange': isPasswordLogin }"
                            @click="isPasswordLogin = true">
                            密码登录
                        </button>
                        <button :class="{ active: !isPasswordLogin, 'text-orange': !isPasswordLogin }"
                            @click="isPasswordLogin = false">
                            邮箱登录
                        </button>
                    </div>

                    <!-- 密码登录表单 -->
                    <div class="password-login" v-show="isPasswordLogin">
                        <select class="country-code">
                            <option value="+86">+86</option>
                            <option value="+86">台湾</option>
                            <option value="+86">香港</option>
                            <option value="+86">澳门</option>
                            <option value="+86">美国</option>
                            <option value="+86">日本</option>
                        </select>
                        <input type="text" placeholder="请输入手机号" class="input-item1" v-model="phone" />
                        <div class="password-row">
                            <input type="password" placeholder="请输入登录密码" class="input-item2" v-model="pwd"
                                @keyup.enter="handleLogin" />
                            <button class="Forgetpd" @click="handforget">忘记密码</button>
                        </div>
                    </div>

                    <!-- 邮箱验证码登录表单 -->
                    <div class="sms-login" v-show="!isPasswordLogin">
                        <div class="phone-row">
                            <input type="text" placeholder="请输入邮箱" class="input-item3" v-model="email" />
                        </div>
                        <div class="code-row">
                            <input type="text" placeholder="请输入验证码" class="input-item4" v-model="code" />
                            <button class="get-code-btn" @keyup.enter="handleLogin" @click="handleGetSmsCode"
                                :disabled="countdown > 0" :class="{ 'is-loading': countdown > 0 }">
                                {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
                            </button>
                        </div>
                    </div>

                    <button class="login-btn" @click="handleLogin">登录</button>
                    <div class="extra-options">
                        <span @click="handleRegister">免费注册</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onUnmounted, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 状态管理
const isPasswordLogin = ref(true); // 登录方式切换
const phone = ref(''); // 手机号
const pwd = ref(''); // 密码
const email = ref(''); // 邮箱
const code = ref(''); // 验证码
const countdown = ref(0); // 倒计时
const timer = ref(null); // 定时器实例

const router = useRouter();

// 页面挂载时禁止滚动
onMounted(() => {
    document.body.style.overflowY = 'hidden';
    document.documentElement.style.overflowY = 'hidden';
});

// 页面卸载时清理定时器和恢复滚动
onUnmounted(() => {
    document.body.style.overflowY = '';
    document.documentElement.style.overflowY = '';
    if (timer.value) clearInterval(timer.value);
});

// 处理登录
const handleLogin = async () => {
    let requestUrl = '/api/login';
    let requestData;

    // 表单验证
    if (isPasswordLogin.value) {
        if (!phone.value) return alert('请输入手机号');
        if (!pwd.value) return alert('请输入密码');
        requestData = { phone: phone.value, pwd: pwd.value };
    } else {
        if (!email.value) return alert('请输入邮箱');
        if (!checkEmailFormat(email.value)) return alert('请输入正确的邮箱格式');
        if (!code.value) return alert('请输入验证码');
        requestUrl = '/api/emaillogin';
        requestData = { email: email.value, code: code.value };
    }

    try {
        // 发送登录请求
        const response = await axios.post(
            `http://127.0.0.1:9001${requestUrl}`,
            requestData
        );

        const data = response.data;
        if (data.message.includes('successful')) {
            localStorage.setItem('userInfo', JSON.stringify(data.user));
            router.push('/Chat');
        } else {
            alert(data.error || '登录失败，请重试');
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        alert(error.response?.data?.error || '网络错误，请稍后重试');
    }
};

// 处理获取验证码
const handleGetSmsCode = async () => {
    // 邮箱格式验证
    if (!email.value) return alert('请输入邮箱');
    if (!checkEmailFormat(email.value)) return alert('请输入正确的邮箱格式（例如：xxx@qq.com）');

    try {
        const response = await axios.post(
            'http://127.0.0.1:9001/api/send-email-code',
            { email: email.value }
        );

        // 打印完整响应数据，便于调试
        console.log('API响应:', response.data);

        if (response.data.message === 'Verification code sent successfully') {
            alert('验证码已发送至您的邮箱，请注意查收（有效期10分钟）');
            startCountdown();
        } else {
            alert('发送失败：' + (response.data.error || '未知错误'));
        }
    } catch (error) {
        console.error('发送验证码失败：', error);
        alert(error.response?.data?.error || '网络错误，无法发送验证码');
    }
};
// 邮箱格式验证
const checkEmailFormat = (email) => {
    const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return reg.test(email);
};

// 开始倒计时
const startCountdown = () => {
    // 清除旧定时器
    if (timer.value) clearInterval(timer.value);

    countdown.value = 60;
    timer.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            clearInterval(timer.value);
            timer.value = null;
        }
    }, 1000);
};

// 处理注册跳转
const handleRegister = () => {
    router.push('ZhuCe');
};
const handforget = () => {
    router.push('Forget');
};
</script>

<style scoped>
.text-orange {
    color: #ff6200;
}

.yemian {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #f0eff2;
    margin: 0;
    padding: 0;
}

.header {
    width: 100%;
    height: 88px;
    background-color: #f0eff2;
    margin-bottom: 84px;
    display: flex;
    align-items: center;
}

.img1 {
    width: 116px;
    height: 64px;
    margin-left: 44px;
}

.bigbox {
    background-color: #ffffff;
    width: 866px;
    height: 517px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.content {
    width: 706px;
    height: 360px;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
}

/* 左侧扫码区域样式 */
.saoma {
    width: 195px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.ma-tltle {
    font-family: PingFang SC;
    font-size: 22px;
    font-weight: 500;
    line-height: 22px;
    margin-bottom: 20px;
}

.img2 {
    width: 167px;
    height: 167px;
    margin: 15px 14px 30px 14px;
    border: 1px solid #eee;
    padding: 10px;
    border-radius: 8px;
}

.ma-how {
    width: 196px;
    height: 80px;
    flex-direction: column;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.dakai,
.dianji {
    font-size: 12px;
    color: #8891a2;
}

.app {
    color: #ff6200;
    font-size: 12px;
}

.where {
    font-size: 14px;
    font-weight: 400;
    line-height: 18px;
    color: #6c6c6c;
}

/* 右侧登录表单样式 */
.denglu {
    width: 350px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.ways {
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
    gap: 20px;
}

.ways button {
    border: none;
    outline: none;
    font-size: 22px;
    font-weight: 500;
    line-height: 22px;
    height: 22px;
    background-color: #fff;
    cursor: pointer;
    transition: color 0.3s;
}

.ways button.active::after {
    content: '';
    position: absolute;
    bottom: -8px;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #ff6200;
}

/* 输入框样式 */
.country-code {
    width: 65px;
    background-color: #f3f6f8;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    height: 48px;
    cursor: pointer;
    border: none;
    outline: none;
    padding: 0 10px;
}

.input-item1 {
    width: 285px;
    margin-top: 30px;
    margin-bottom: 20px;
    background-color: #f3f6f8;
    border-radius: 4px;
    box-sizing: border-box;
    height: 48px;
    border: none;
    outline: none;
    padding: 0 15px;
}

.password-row {
    width: 350px;
    height: 48px;
    align-items: center;
    margin-bottom: 55px;
    display: inline-flex;
}

.Forgetpd {
    width: 90px;
    height: 48px;
    background-color: #f3f6f8;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    cursor: pointer;
    color: #ff6200;
    font-size: 14px;
    font-weight: 500;
    border: none;
    outline: none;
    display: flex;
    align-items: center;
    justify-content: center;

}

.input-item2 {
    width: 350px;
    background-color: #f3f6f8;
    border-radius: 4px;
    box-sizing: border-box;
    height: 48px;
    border: none;
    outline: none;
    padding: 0 15px;
}

.phone-row {
    margin-bottom: 20px;
    margin-top: 30px;
    width: 360px;
    height: 48px;
    display: inline-flex;
}

.input-item3 {
    margin-bottom: 20px;
    width: 345px;
    background-color: #f3f6f8;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    height: 48px;
    border: none;
    outline: none;
    padding: 0 15px;
}

.code-row {
    margin-bottom: 55px;
    width: 360px;
    height: 48px;
    display: inline-flex;
}

.input-item4 {
    width: 260px;
    background-color: #f3f6f8;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    box-sizing: border-box;
    height: 48px;
    border: none;
    outline: none;
    padding: 0 15px;
}

/* 验证码按钮样式 */
.get-code-btn {
    width: 100px;
    height: 48px;
    background-color: #f3f6f8;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    cursor: pointer;
    color: #ff6200;
    font-size: 14px;
    font-weight: 500;
    border: none;
    outline: none;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
}

.get-code-btn:disabled {
    color: #8891a2;
    background-color: #e9ecef;
    cursor: not-allowed;
}

/* 加载状态动画 */
.is-loading {
    position: relative;
    overflow: hidden;
}

.is-loading::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    animation: loading 1.5s infinite;
}

@keyframes loading {
    0% {
        transform: translateX(-100%);
    }

    100% {
        transform: translateX(100%);
    }
}

/* 登录按钮 */
.login-btn {
    font-size: 16px;
    height: 48px;
    width: 100%;
    padding: 10px;
    background-color: #ff6200;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 20px;
    transition: background-color 0.3s;
}

.extra-options {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
}

.extra-options span {
    color: #333;
    cursor: pointer;
    font-size: 12px;
    transition: color 0.3s;
}

/* 基础样式重置 */
body,
html {
    overflow-y: hidden !important;
    height: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
}

/* 隐藏滚动条（针对webkit浏览器） */
::-webkit-scrollbar {
    display: none !important;
}
</style>